package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.WechatTemplateMessageService;
import com.yixun.qfbao.api.service.WxmsgFailureApiService;
import com.yixun.qfbao.model.WxmsgFailure;
import com.yixun.qfbao.model.dto.WxmsgFailureDto;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.service.WxmsgFailureService;
import com.yixun.qfbao.util.TemplateMessageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WxmsgFailureApiServiceImpl implements WxmsgFailureApiService {

    private static final Logger logger = LoggerFactory.getLogger(WxTemplateMsgServiceImpl.class);

    @Autowired
    private WechatTemplateMessageService wechatTemplateMessageService;
    @Autowired
    private WxmsgFailureService wxmsgFailureService;

    @Override
    public TemplateMessageResult sendFailureWxmsgAgain(WxmsgFailure reqDto, String accessToken) {
        TemplateMessageResult result = new TemplateMessageResult();
        try {
            String receiveContent = reqDto.getReceiveContent();
            logger.info("sendFailureWxmsgAgain start accesstoken {}, content {}", accessToken, receiveContent);
            result = wechatTemplateMessageService.sendTemplate(accessToken, receiveContent);
            WxmsgFailureDto wfDto = new WxmsgFailureDto();
            wfDto.setId(reqDto.getId());
            if("ok".equals(result.getErrmsg().toLowerCase())) {
                wfDto.setSendStatus(SendStatusEnum.SUCCESS.getNo());
            }
            wfDto.setRepeatResult(JSONObject.toJSONString(result));
            wxmsgFailureService.update(wfDto);
            logger.info("sendFailureWxmsgAgain end result {}", JSONObject.toJSONString(result));
        } catch (Exception ex) {
            logger.error("sendFailureWxmsgAgain---- 发送微信模板消息失败：{}", ex);
        }
        return result;
    }
}
